import { Toast } from 'antd-mobile-v2'
import axios from 'axios'
import { getTokenInfo, setTokenInfo } from './storage'
import history from './history'
import store from '@/store'
import { logout, setToken } from '@/store/actions/login'
export const baseLink = 'http://geek.itheima.net'

// 1. 创建新的 axios 实例
const instance = axios.create({
  baseURL: `${baseLink}/v1_0`,
})

// 2. 设置请求拦截器和响应拦截器
instance.interceptors.request.use((config) => {
  const token = getTokenInfo().token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    const { token, refresh_token } = getTokenInfo()
    const config = error.config
    // const dispatch = useDispatch()
    if (error?.response?.status === 401) {
      if (!token || !refresh_token) {
        history.replace({
          pathname: '/login',
          state: {
            pathname: history.location.pathname,
          },
        })
        return Promise.reject(error)
      }

      try {
        const res = await axios.put(
          config.baseURL + 'authorizations',
          {},
          { headers: { Authorization: `bearer ${refresh_token}` } }
        )
        console.log(res)
        const newToken = res.data.data.token
        // (1)更新到本地，更新到redux中
        setTokenInfo({
          token: newToken,
          refresh_token,
        })
        store.dispatch(
          setToken({
            token: newToken,
            refresh_token,
          })
        )
        // (2)重新发请求 => 这里需要return，return给页面，将正确的结果return给页面
        return instance(config)
      } catch {
        // (1) 清楚无效token(本地，redux => 退出)， refresh_token都无效
        store.dispatch(logout())
        // (2) 跳转登录
        history.replace({
          pathname: '/login',
          state: {
            pathname: history.location.pathname,
          },
        })
      }
    }

    // 通用错误处理, 要放在最后面
    if (error?.response?.data?.message) {
      Toast.info(error.response.data.message)
    } else {
      Toast.info('服务器繁忙, 请稍后重试')
    }
    return Promise.reject(error)
  }
)

// 3. 导出该 axios 实例
export default instance
